//
//  ST_LiveBeautyDispatcher.swift
//  btvideo
//
//  Created by mac on 2021/3/19.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import PINRemoteImage
import SwiftyJSON
import SwiftyUserDefaults
import SwifterSwift
import RxCocoa
import RxSwift



class ST_LiveBeautyWidget: NSObject {
    
    /**
     通话结束删除在上墙的数据  Info = ["accid":"defcc8cd805936f7ddbf0e7da49a4ebd"]
     */
    static let delete_live_queue_notification: NSNotification.Name = NSNotification.Name.init("ST_LiveBeautyWidget_refreshLiveQueueNotification")
    
    //MARK: - Share Instance
    static let shared = ST_LiveBeautyWidget()
    
    var disposeBag = DisposeBag()
    
    private override init() {
        super.init()
        
        binding()
        
        timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(request_count_of_pools), userInfo: nil, repeats: true)
    }
    
    func binding(){
        
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().subscribe(onNext: { f in
        print("SCComponets.login_status_did_changed_observable()")
             if f == true{
                 self.request_count_of_pools()
             }
         }).disposed(by: rx.disposeBag)
       
        
        layout_live_beauty_behavior.subscribe(onNext: { layoutRootView in
            
            if let v = layoutRootView{
                self.layout_dispatcher_view(root_view: v)
            }
            
        }).disposed(by: disposeBag)
        
        
        let statusChanged = ST_BTUserInfoManager.shared.app_chat_status_behavior.distinctUntilChanged({ $0.rawValue == $1.rawValue })
        
        statusChanged.observe(on: MainScheduler.instance)
            .subscribe(onNext: { status in
            
            switch status {
            case .fallInVideoQueue,.fallInVoiceQueue:
                //            dispatcher_view.alpha = 1
                
                self.dispatcher_view.isUserInteractionEnabled = false
                
                self.start_up_live_queue_btn.alpha = 0
                
                self.up_live_square_btn.alpha = 0
                self.dispatcher_view.alpha = 1
                
                self.count_of_pools_view.alpha = 0
                self.my_match_text_view.alpha = 1
                self.my_match_close_btn.alpha = 1
                
                self.back_gradient_view.model = status.rawValue == 2  ? self.my_video_matching_model : self.my_voice_matching_model
                
            
                
                
            default:
                
                self.my_create_room = nil
                
                self.dispatcher_view.isUserInteractionEnabled = true
                
                self.start_up_live_queue_btn.alpha = 1
                
                if self.count_in_pools_behavior.value > 0 {
                    
                    self.up_live_square_btn.alpha = 0
                    self.dispatcher_view.alpha = 1
                    
                    self.count_of_pools_view.alpha = 1
                    self.my_match_text_view.alpha = 0
                    self.my_match_close_btn.alpha = 0
                    
                    self.back_gradient_view.model = self.normal_gradient_model
                    
                    self.count_of_pools_content_label.text = self.count_in_pools_behavior.value.string + "人正在等待通话"
                    
                    
                }else{
                    self.up_live_square_btn.alpha = 1
                    self.dispatcher_view.alpha = 0
                    self.my_match_close_btn.alpha = 0
                }
                
            }
            
            self.bind_data()
            
            self.push_live_status_to_remote()
            
        }).disposed(by: disposeBag)
        
        
        self.count_in_pools_behavior.observe(on: MainScheduler.instance).subscribe(onNext: { count in
            
            switch ST_BTUserInfoManager.shared.app_chat_status_behavior.value{
                
            case .fallInVideoQueue,.fallInVoiceQueue: break
                    
            default:
                
                if self.count_in_pools_behavior.value > 0 {
                    
                    self.up_live_square_btn.alpha = 0
                    self.dispatcher_view.alpha = 1
                    
                    self.count_of_pools_view.alpha = 1
                    self.my_match_text_view.alpha = 0
                    self.my_match_close_btn.alpha = 0
                    
                    self.back_gradient_view.model = self.normal_gradient_model
                    
                    self.count_of_pools_content_label.text = self.count_in_pools_behavior.value.string + "人正在等待通话"
                    
                    
                }else{
                    self.up_live_square_btn.alpha = 1
                    self.dispatcher_view.alpha = 0
                    self.my_match_close_btn.alpha = 0
                }
            }
            
        }).disposed(by: disposeBag)
        
     
    }
    
    //MARK: - Properties
    
    var count_in_pools_behavior = BehaviorRelay<Int>(value: 0)
    
    ///布局
    var layout_live_beauty_behavior = BehaviorRelay<UIView?>(value: nil)
    
    
    fileprivate var timer:Timer?
    
//    fileprivate var lastStatus:ST_TIAN_MEDIA_SATE_ENUM?
//
//    var status = ST_TIAN_MEDIA_SATE_ENUM.none{
//        didSet{
//
//            if let last = lastStatus{
//
//                if last.rawValue != status.rawValue {
//
//                    modifyUIStatus()
//                }
//
//            }else{
//
//                modifyUIStatus()
//            }
//
//            lastStatus = status
//        }
//    }
    
    
    fileprivate var modify_my_room_sign:ST_LiveBeautyCellModel?
    
    fileprivate(set) var my_create_room:ST_LiveBeautyCellModel?{
        didSet{
            if let last = modify_my_room_sign{
                
                if last != my_create_room {
                    NotificationCenter.default.post(name: Notification.Name.InsertMyCreateRoom, object: nil)
                }
            }else{
                NotificationCenter.default.post(name: Notification.Name.InsertMyCreateRoom, object: nil)
            }
            
            modify_my_room_sign = my_create_room
        }
    }
    
    //    其他界面的按钮  弃用
    lazy var start_up_live_queue_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        //        默认隐藏
        control.alpha = 0
        
        control.setImageForAllStates(ST_ImageUtils.imageName("startUpCPQueue")!)
        
        control.addTarget(self, action: #selector(up_live_square_handle(sender:)), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    fileprivate lazy var last_tab_control_tag = 0
    
    fileprivate let red_sign_view_width = 12.cgFloat
    
    fileprivate lazy var red_sign_view:UIView = {
        let control = UIView()
        control.cornerRadius = red_sign_view_width/2.0
        control.backgroundColor = UIColor.init(hex: 0xFF5F5F)
        control.borderColor = .white
        control.borderWidth = 2
        return control
    }()
    
    fileprivate lazy var dispatcher_view:UIControl = {
        let control = UIControl()
        control.cornerRadius = 42/2.0
        control.alpha = 0
        control.addTarget(self, action: #selector(push_current_list_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var normal_gradient_model = ST_FWGradientViewModel.init(colors: [UIColor.init(hex: 0xFEC207)!,UIColor.init(hex: 0xFEC207)!], startPoint: CGPoint(x: 0, y: 0.5), endPoint: CGPoint(x: 0.5, y: 0.5))
    
    fileprivate lazy var my_video_matching_model = ST_FWGradientViewModel.init(colors: [UIColor.init(hex: 0x48C6EF)!,UIColor.init(hex: 0x7995F8)!], startPoint: CGPoint(x: 0, y: 0.5), endPoint: CGPoint(x: 0.5, y: 0.5))
    
    fileprivate lazy var my_voice_matching_model = ST_FWGradientViewModel.init(colors: [UIColor.init(hex: 0xFE576D)!,UIColor.init(hex: 0xFF78A9)!], startPoint: CGPoint(x: 0, y: 0.5), endPoint: CGPoint(x: 0.5, y: 0.5))
    
    fileprivate lazy var back_gradient_view:ST_FWGradientView = {
        let control = ST_FWGradientView()
        control.isUserInteractionEnabled = false
        return control
    }()
    
    fileprivate lazy var avatar_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = 34/2.0
        control.borderColor = .white
        control.borderWidth = 1
        control.animationDuration = 0.5
        return control
    }()
    
    fileprivate lazy var up_live_square_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("NoneOfPersonInLivePools")!)
        control.alpha = 0
        control.addTarget(self, action: #selector(up_live_square_handle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    
    
    fileprivate lazy var my_match_text_view:UIView = {
        let control = UIView()
        control.isUserInteractionEnabled = false
        control.alpha = 0
        control.addSubview(my_match_title_label)
        
        my_match_title_label.snp.makeConstraints { (make) in
            make.left.centerY.equalToSuperview()
        }
        return control
    }()
    
    fileprivate lazy var count_of_pools_view:UIView = {
        let control = UIView()
        control.isUserInteractionEnabled = false
        control.alpha = 0
        control.addSubview(count_of_pools_title_label)
        control.addSubview(count_of_pools_content_label)
        count_of_pools_title_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalToSuperview().offset(4)
            make.height.equalTo(17)
        }
        
        count_of_pools_content_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.bottom.equalToSuperview().offset(-4)
            make.height.equalTo(16)
        }
        
        return control
    }()
    
    fileprivate lazy var count_of_pools_title_label:UILabel = {
        let control = UILabel.init()
        control.text = "与你匹配的"
        control.textColor = UIColor.white
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var count_of_pools_content_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor.white
        control.font = UIFont.systemFont(ofSize: 11, weight: UIFont.Weight.regular)
        return control
    }()
    
    
    fileprivate lazy var my_match_title_label:UILabel = {
        let control = UILabel.init()
        control.text = "正在匹配中"
        control.textColor = UIColor.white
        control.font = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.medium)
        return control
    }()
    
    
    fileprivate lazy var my_match_close_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.alpha = 0
        control.setImageForAllStates(ST_ImageUtils.imageName("匹配关闭_icon")!)
        
        control.addTarget(self, action: #selector(stop_my_match_handle), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    //MARK: - Private Method
    
    @objc fileprivate func push_setting_beauty_filter_controller(){
        
        //        print("跳转美颜设置")
        
        //        self.up_live_square_btn.isUserInteractionEnabled = false
        //
        //        main_thread_execute(afterDelay: 1.5) {
        //            self.up_live_square_btn.isUserInteractionEnabled = true
        //        }
        
        
        
        MobClick.event("StartVoiceOrVideoChat", attributes: ["按钮类型":"美颜设置"])
        
        GlobalPresent(toController: ST_SettingBeautyFIlterController())
        
        
    }
    
    @objc func up_live_square_handle(sender:UIButton){
        
        red_sign_view.isHidden = true
        
        sender.isUserInteractionEnabled = false
        
        main_thread_execute(afterDelay: 1.5) {
            sender.isUserInteractionEnabled = true
        }
        
//        MobClick.event("StartVoiceOrVideoChat", attributes: ["按钮类型":"我要组CP"])
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self.dispatcher_view.parentViewController) {
            return
        }
        
        guard let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo else { return  }
        
        
        let tipsKey = user.accid + "_4324892347923491328921"
        
        if Defaults.bool(forKey: tipsKey) || Defaults[.isPanda]{
            toast_up_live_options()
            return
        }
        
        
        let vc = ST_EngagementFemaleTipsViewController()
        
        vc.overCurrentContext = true
        
        vc.confirm_closure = {
            self.toast_up_live_options()
        }
        
        GlobalPresent(toController: vc, animated: false)
        
        Defaults.set(true, forKey: tipsKey)
        
        Defaults.synchronize()
        
    }
    
    fileprivate func toast_up_live_options(){
        
        /*
        let alert = ST_UpLiveSquareOptionsController()
        
        
        */
        
        let alert = ST_JoinRoomOptionsController()
        
        alert.overCurrentContext = true
        
        alert.over_current_context_alpha = "0.4"
        
        GlobalPresent(toController: alert)
    }
    
    @objc func push_current_list_handle(){
        
        red_sign_view.isHidden = true
        
        GlobalPresent(toController: ST_WaitChatRankViewController())
        
    }
    
    @objc func stop_my_match_handle(){
        
        cancel_match_game()
        
        /*
        if Defaults[.isPanda]{
            cancel_match_game()
            return
        }
        
        
        let alert = BTVerticalAlertViewController.stopMatchingAlert()
        
        alert.cancel_closure = {[weak self] in
            self?.cancel_match_game()
        }
        
        GlobalPresent(toController: alert)
        */
    }
    
    
    
    @objc fileprivate func push_live_status_to_remote(){
        
        //取消延时任务
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(push_live_status_to_remote), object: nil)
        
        guard let token = ST_BTUserInfoManager.shared.current_account_info?.token, token.count > 2 else {
            return
        }
        
        let status = ST_BTUserInfoManager.shared.app_chat_status_behavior.value
        
        var pushStatus = status.rawValue
        
        //        其他情况设置到后台都是忙碌中
        if pushStatus > 3 {
            pushStatus = 3
        }
        
        var api = ""
        
        var paramters = ["state":pushStatus.string]
        
        switch status {
        case .fallInVideoQueue(let themeId,let sign):
            api = PH.createLiveRoomApi
            paramters.updateValue(2.string, forKey: "type")
            if let id = themeId{
                paramters.updateValue(id.string, forKey: "theme_id")
            }
            if let str = sign{
                paramters.updateValue(str, forKey: "name")
            }
        case .fallInVoiceQueue(let themeId,let sign):
            api = PH.createLiveRoomApi
            paramters.updateValue(1.string, forKey: "type")
            if let id = themeId{
                paramters.updateValue(id.string, forKey: "theme_id")
            }
            if let str = sign{
                paramters.updateValue(str, forKey: "name")
            }
        case .none:
            api = PH.cancelMatchGameApi
        default:
            api = PH.changeLiveBeautyStatusApi
        }
        
        /*
        if status == .fallInVideoQueue{
            api = PH.matchEngagementVideoApi
        }else if status == .fallInVoiceQueue{
            api = PH.matchEngagementVoiceApi
        }else if status == .none{
            api = PH.cancelMatchGameApi
        }*/
        
        
        let resultStr = "------------------\(Date())\n api=" + api + "--param:" + String(describing: paramters)
        
        print(resultStr, to: &todayMatchingLogger)
        
        JVrequest(api,parameters: paramters) { (json) in
            
//            print("[liveBeauty]-json：",json)
            if api.contains("createRoom"){
                // RS 数据格式变动
                self.my_create_room = ST_LiveBeautyCellModel.init(creatRoomFromJson: json["data"])
            }
            
            
            
            let successStr = "------------------\(Date())\n api=" + api + "--success json:" + (json.rawString() ?? "")
            
            print(successStr, to: &todayMatchingLogger)
            
        } failure: { (code, err) in
            
            let errStr = "------------------\(Date())\n api=" + api + "--err :" + err
            
            print(errStr, to: &todayMatchingLogger)
            
            /// 调用失败
            self.perform(#selector(self.push_live_status_to_remote), with: nil, afterDelay: 2)
            
        }
        
        
    }
    
    fileprivate func bind_data(){
        
        avatar_image_view.pin_setImage(from: ST_BTUserInfoManager.shared.current_account_info?.userinfo?.avatar.compress_small_image(width: 34*3).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        
    }
    
    fileprivate let widgetView = UIView()
    
    
    @objc fileprivate func layout_dispatcher_view(root_view:UIView){
        
        if widgetView.superview == root_view {
            return
        }
        
        root_view.addSubview(widgetView)
        widgetView.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.height.equalTo(42)
            make.width.equalTo(148+21+24)
            make.bottom.equalToSuperview().offset(-118-BTSafeAreaBottom)
        }
        
        [dispatcher_view,my_match_close_btn,up_live_square_btn,red_sign_view].forEach({ widgetView.addSubview($0) })
        
        dispatcher_view.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(42/2.0)
            make.height.equalTo(42)
            make.width.equalTo(148+21)
            make.bottom.equalToSuperview()
        }
        
        dispatcher_view.addSubview(back_gradient_view)
        back_gradient_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        dispatcher_view.addSubview(avatar_image_view)
        avatar_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(34)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(4)
        }
        
        dispatcher_view.addSubview(my_match_text_view)
        my_match_text_view.snp.makeConstraints { (make) in
            make.left.equalTo(avatar_image_view.snp.right).offset(5)
            make.centerY.equalToSuperview()
            make.height.equalToSuperview()
            make.right.equalToSuperview().offset(-42/2.0)
        }
        
        dispatcher_view.addSubview(count_of_pools_view)
        count_of_pools_view.snp.makeConstraints { (make) in
            make.left.equalTo(avatar_image_view.snp.right).offset(5)
            make.top.bottom.equalToSuperview()
            make.right.equalToSuperview()
        }
        
        
        my_match_close_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(my_match_text_view)
            make.width.height.equalTo(34)
            make.right.equalTo(my_match_text_view)
        }
        
        
        
        
        
        
        up_live_square_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(dispatcher_view)
            make.right.equalToSuperview()
            make.width.equalTo(153)
            make.height.equalTo(42)
        }
        
        
        red_sign_view.snp.makeConstraints { (make) in
            make.centerY.equalTo(dispatcher_view.snp.top)
            make.left.equalTo(dispatcher_view).offset(5)
            make.width.height.equalTo(red_sign_view_width)
        }
    }
    
    
    
    
    //MARK: - Public Method
    func change_widget_state(tabControlTag:Int)  {
        
//        0 1 2
        /*
        if tabControlTag < 2{
            
            
            red_sign_view.alpha = 1
            
            dispatcher_view.isHidden = false
            my_match_close_btn.isHidden = false
            up_live_square_btn.isHidden = false
            
            start_up_live_queue_btn.alpha = 0
            
        }else if tabControlTag == 2{
            
            red_sign_view.alpha = 0
            //            自己不在墙上 隐藏
            if [2,1].contains(status.rawValue) == false{
//            if status != .fallInVoiceQueue && status != .fallInVideoQueue{
                
                dispatcher_view.isHidden = true
                my_match_close_btn.isHidden = true
                start_up_live_queue_btn.alpha = 1
                
            }else{
                
                start_up_live_queue_btn.alpha = 0
                
                dispatcher_view.isHidden = false
                my_match_close_btn.isHidden = false
            }
            
            up_live_square_btn.isHidden = true
            
        }else{
            
            red_sign_view.alpha = 0
            
            start_up_live_queue_btn.alpha = 0
            
            dispatcher_view.isHidden = true
            up_live_square_btn.isHidden = true
        }*/
        
        let status = ST_BTUserInfoManager.shared.app_chat_status_behavior.value
        
        if [0,2].contains(tabControlTag){
            
            red_sign_view.alpha = 1
            
            dispatcher_view.isHidden = false
            my_match_close_btn.isHidden = false
            up_live_square_btn.isHidden = false
            
            start_up_live_queue_btn.alpha = 0
            
        }else if tabControlTag == 1{
         
//            在墙上 显示
            if [2,1].contains(status.rawValue){
                
                red_sign_view.alpha = 1
                
                dispatcher_view.isHidden = false
                my_match_close_btn.isHidden = false
                up_live_square_btn.isHidden = false
                
                start_up_live_queue_btn.alpha = 0
                
            }else{
                
                red_sign_view.alpha = 0
                
                start_up_live_queue_btn.alpha = 0
                
                dispatcher_view.isHidden = true
                up_live_square_btn.isHidden = true
            }
            
            
            
        }else{
            
            red_sign_view.alpha = 0
            
            start_up_live_queue_btn.alpha = 0
            
            dispatcher_view.isHidden = true
            up_live_square_btn.isHidden = true
            my_match_close_btn.isHidden = true
        }
        
        
        last_tab_control_tag = tabControlTag
    }
    
    
    /**
     改变上墙状态 return [false 不能进行下一步,true 进行下一步]
     */
    func settingUpLiveSquare(isVideo:Bool,fromController:UIViewController?,themeId:Int?,sign:String?)->Observable<Bool>{
        
        
        let setupObservable = settingUpLiveSquareAfterTips(isVideo: isVideo, fromController: fromController, themeId: themeId, sign: sign)
        
        
//#if DEBUG
//
//        let vc = ST_LiveBeautyRulesController(isVideo: isVideo)
//
//        GlobalPresent(toController: vc)
//
//        return vc.nextStep.flatMapLatest { _ in
//            return setupObservable
//        }
//
//#else
  
        // 如果没有展示过规则    语音||视频
        if (isVideo && !Defaults[.videoRulesToasted]) || (!isVideo && !Defaults[.voiceRulesToasted]){
            
            let vc = ST_LiveBeautyRulesController(isVideo: isVideo)
            
            GlobalPresent(toController: vc)
            
            return vc.nextStep.flatMapLatest { _ in
                return setupObservable
            }
        }
        
        
        return setupObservable
          
//#endif
        
        
    }
    
    func settingUpLiveSquareAfterTips(isVideo:Bool,fromController:UIViewController?,themeId:Int?,sign:String?)->Observable<Bool>{
        
        
        let single:Observable<Bool> = Observable.create { observer -> Disposable in
            
            if ST_BTUserInfoManager.shared.app_chat_status_behavior.value.rawValue != 0{
                fromController?.toast(text: "当前不能使用该功能")
                observer.onNext(false)
                observer.onCompleted()
                return Disposables.create()
            }
            
            
            if ST_BTUserInfoManager.shared.additional_attributes?.SMForbidden == true{
                fromController?.toast(text: "处罚期间，禁止使用该功能！")
                observer.onNext(false)
                observer.onCompleted()
                return Disposables.create()
            }
            
            if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: fromController) {
                observer.onNext(false)
                observer.onCompleted()
                return Disposables.create()
            }
            
            guard let attributes = ST_BTUserInfoManager.shared.additional_attributes, let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo else {
                
                observer.onNext(false)
                observer.onCompleted()
                
                return Disposables.create()
            }
            
            
            /// 新需求
            if attributes.firstImpressionCount > 0 &&  Defaults[.isPanda] == false && user.sweet_coin > 0.99 && user.sex == .male{
                
                let status:ST_TIAN_MEDIA_SATE_ENUM = isVideo ? .fallInVideoQueue(themeId: themeId, sign: sign) : .fallInVoiceQueue(themeId: themeId, sign: sign)
                
                ST_BTUserInfoManager.shared.updateapp_chat_status(value: status)
                
                
                ST_LiveBeautyWidget.shared.change_widget_state(tabControlTag: ST_LiveBeautyWidget.shared.last_tab_control_tag)
               
                observer.onNext(true)
                observer.onCompleted()
                return Disposables.create()
            }
            
            //        男生小于25 不能上墙 或者没有免费次数了
            if user.sex == .male && user.sweet_coin < 25 && attributes.liveTalkFreeNumber < 1 && Defaults[.isPanda] == false{
                
                let msg = SCComponets.rich_text_storage_component.json["up_live_alert"]["content"].stringValue
                
                ST_MaidWayManager.shared.source = .男生上墙
                
                ST_RechargeViewController.toast(content: msg)
                
                observer.onNext(false)
                observer.onCompleted()
                return Disposables.create()
                
            }else if user.sex == .female && FACE_AVATAE_STATE != 3{
                
                ToastDetectFaceTips(vcCreater: nil)
                
                observer.onNext(false)
                observer.onCompleted()
                return Disposables.create()
                
            }else{
                
                let status:ST_TIAN_MEDIA_SATE_ENUM = isVideo ? .fallInVideoQueue(themeId: themeId, sign: sign) : .fallInVoiceQueue(themeId: themeId, sign: sign)
                
                ST_BTUserInfoManager.shared.updateapp_chat_status(value: status)
                
                
                ST_LiveBeautyWidget.shared.change_widget_state(tabControlTag: ST_LiveBeautyWidget.shared.last_tab_control_tag)
               
                observer.onNext(true)
                observer.onCompleted()
                return Disposables.create()
            }
        }
        
        return single
        
    }
    
    func cancel_match_game(){
        
        ST_BTUserInfoManager.shared.updateapp_chat_status(value: .none)
        
        change_widget_state(tabControlTag: last_tab_control_tag)
      
    }
    
    
    
    @objc fileprivate func request_count_of_pools(){
        
        if ST_BTUserInfoManager.shared.current_account_info?.token.count ?? 0 < 2{
            return
        }
        
        
        
        #if DEBUG
            return
        #else
        
            JVrequest(PH.countOfLivePoolsApi) { (json) in
                
                self.count_in_pools_behavior.accept(json["data"]["count"].intValue)
                
            } failure: { (code, err) in
                
            }
        
        #endif
        
        
        
        
    }
    
}

